package com.cipe.cmrs.controllers;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cipe.cmrs.model.User;
import com.cipe.cmrs.model.ref.LinkCategory;
import com.cipe.cmrs.service.UserService;
import com.cipe.cmrs.service.ref.EntityRefService;

@Controller
public class DashboardController extends BaseController {

	private static final long serialVersionUID = 2953245877386975346L;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private EntityRefService entityRefService;

	@RequestMapping("/secure/showDashboard.do")
	public String showLogin(HttpServletRequest request, Model model) {
		User user = userService.findById(getUserId(request));
		if(user == null){
			return "redirect:/../showLogin.do";
		}
		model.addAttribute("user", user);
		model.addAttribute("linkCategories", entityRefService.findAllByType(LinkCategory.class));
		return "dashboard";
	}
	
	@RequestMapping("/secure/showChangePassword.do")
	public String showChangePassword(HttpServletRequest request, Model model) {
		User loggedInUser = userService.findById(getUserId(request));
		User user = new User();
		user.setLoginName(loggedInUser.getLoginName());
		model.addAttribute("user", user);
		return "changePassword";
	}
	
	@RequestMapping("/secure/changePassword.do")
	public String changePassword(@ModelAttribute User user, BindingResult result, Model model) {
		if(userService.changePassword(user)){
			result.rejectValue("id", "changePassword.message.success");
		} else {
			result.reject("changePassword.message.error");
		}
		user.setPassword(null);
		user.setConfirmPassword(null);
		user.setNewPassword(null);
		model.addAttribute("user", user);
		return "changePassword";
	}
	
	@RequestMapping("/secure/showPageHeading.do")
	public String showPageHeading(@RequestParam String heading, Model model) {
		model.addAttribute("heading", heading);
		return "headingPage";
	}
}
